import pygame
import sys
sys.dont_write_bytecode = True

pygame.init()
Screen = pygame.display.set_mode((1650, 920))
pygame.display.set_caption('Fish game')
FPS = pygame.time.Clock()
f = pygame.font.Font('C:/Windows/Fonts/simhei.ttf', 0x18)
F = pygame.font.Font('C:/Windows/Fonts/simhei.ttf', 0x10)

import config
config.init(Screen, FPS=FPS)
import regular
import traceback
import time
#import faulthandler
import atexit
#faulthandler.enable()
import survival

atexit.register(config.AtExit)

version_keys, v1, v2, v3 = config.version.keys(), 0, 0, 0
ver_vk_len = 3
for i in version_keys:
    if '.' not in i:
        continue
    else:
        li_vk = i.split('.')
        v10, v20, v30 = 1, 3, 1
        if len(li_vk) == 2:
            v10, v20 = int(li_vk[0]), int(li_vk[1])
            v30 = 0
            ver_vk_len = 2
        elif len(li_vk) == 3:
            v10, v20 = int(li_vk[0]), int(li_vk[1])
            v30 = int(li_vk[2])
            if v30 < 10:
                v30 *= 10
            ver_vk_len = 3
        else:
            continue
        if v10 > v1:
            v1, v2, v3 = v10, v20, v30
        elif v10 == v1:
            if v20 > v2:
                v2, v3 = v20, v30
            elif v20 == v2:
                if v30 > v3:
                    v3 = v30
if v3 % 10 == 0:
    v3 /= 10
if type(v3) != int:
    v3 = int(v3)
version = f"{v1}.{v2}.{v3}" if ver_vk_len == 3 else f"{v1}.{v2}"
VERSION = version # config.version["use"]
pygame.display.set_caption(\
    f'Oceancraft {VERSION}{"" if config.version[VERSION]["type"] in ("Release", "release") else " - " + config.version[VERSION]["type"]}')

def start_with(string_former:str, buf:str) -> bool:
    if len(string_former) <= len(buf):
        return False
    else:
        if string_former[0:len(buf)] == buf:
            return True
        else:
            return False


config.Python_vesion = sys.version.split(' ')[0]
for a in sys.argv:
    if '=' not in a:
        continue
    li = a.split('=')
    if len(li) != 2:
        continue
    b, c = li[0], li[1]
    if b == '--Path':
        config.Path = c
    elif b == '--Path1':
        config.Path1 = c
    elif b == '--Path2':
        config.Path2 = c
    elif b == '--gamma':
        config.γ = int(c)
    elif b == '-fpslimit':
        config.fpslimit = int(c)
    elif b == '-gamemode' and c in ('easy', 'hard'):
        config.gamemode = c
    else:
        pass

def winMain():
    config.init(Screen, FPS=FPS)
    # start text
    st = f.render('Press some keys to start game: R--Regular', True, (30, 80, 255))
    while True:
        FPS.tick(8)
        Screen.fill((255,255,255))
        Screen.blit(st, (590, 455))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                config.graphic_isend = True
                return
            elif event.type == pygame.KEYDOWN:
                #if event.key == pygame.K_r:
                #    regular.start()
                #elif ...
                match event.key:
                    case pygame.K_r:
                        regular.start()
                    case pygame.K_s:
                        survival.start()
                    case _:
                        pass
        pygame.display.flip()

#def Quit_finally():
#    pygame.quit()
#atexit.register(Quit_finally)

def write_beta_crash(what:str):
    with open("beta_crash.txt", "a", encoding="UTF-8") as ff:
        ff.write(what)

def write_release_crash(what:str):
    filename = "crash_"
    timenow = time.strftime('%Y-%m-%d_%H.%M.%S', time.localtime()) # crash_2023-7-21_17.54.23.txt
    filename += timenow
    filename += ".txt"
    filepath = "crash_report\\"+filename
    with open(filepath, "a", encoding="UTF-8") as fff:
        fff.write(what)

def Crash_Screen(what: str, dis: str):
    ct: list = []
    ct.append( F.render(f"Game crashed!", True, (255, 255, 0)))
    ct.append( F.render(f"Description: {dis}", True, (255, 0, 0)))
    ct.append( F.render(f" ", True, (255, 255, 0)))
    ct.append( F.render(f"Time: {time.strftime('%Y-%m-%d_%H.%M.%S', time.localtime())}", True, (255, 255, 0)))
    ct.append( F.render(f"version: {VERSION}", True, (255, 255, 0)))
    li = what.split('\n')
    for i in range(len(li)):
        ct.append(F.render(f"{li[i]}", True, (255, 255, 100)))
    ct.append(F.render("Press ESC to quit.", True, (0, 255, 0)))
    if config.version[VERSION]["type"] == 'beta':
        ct.append(F.render('Beta version detected. Type "W" to write the issue to the error report.', True, (10, 255, 0)))
    while True:
        FPS.tick(8)
        Screen.fill((0,0,205))
        for j in range(len(ct)):
            Screen.blit(ct[j], (68, 30 + j * 20))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
                elif event.key == pygame.K_w and config.version[VERSION]["type"] == 'beta':
                    return "write-to-beta"
        pygame.display.flip()

if __name__ == '__main__':
    try:
        winMain()
        config.main_isend = True
        config.graphic_isend = True
    except Exception as e:
        config.Error_Message = traceback.format_exc()
        #traceback.print_exc()
        config.main_isend = True
        config.graphic_isend = True
        if config.version[VERSION]["type"] in ("release", "Release"):
            write_release_crash(f"---------------------------------------------------------------\nCrash!!!\nDescription: {e}\n\n\
                                Time: {time.strftime('%Y-%m-%d_%H.%M.%S', time.localtime())}\nVersion: {VERSION}\n" + config.Error_Message)
        jj = Crash_Screen('\n' + config.Error_Message, f"{e}")
        if jj == 'write-to-beta' and config.version[VERSION]["type"] == 'beta':
            write_beta_crash(f"---------------------------------------------------------------\nCrash!!!\nDescription: {e}\n\n\
                                Time: {time.strftime('%Y-%m-%d_%H.%M.%S', time.localtime())}\nVersion: {VERSION}\n" + config.Error_Message)
    finally:
        qwerty = 1000
        while not config.graphic_isend and qwerty > 0:
            qwerty -= 1
            pygame.time.wait(1)
        pygame.quit()
        sys.exit(0)
"""
计划
加入无尽模式, 加入home, add 'human', 'octopus'
"""